package br.com.tecnoria.controllers
{
	import br.com.tecnoria.vo.CustomerVO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;
	
	public class CustomerController
	{
		[Inject("customerRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var dataprovider:ArrayCollection;
		
		[Bindable]
		public var customer:CustomerVO;
		
		
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="CustomerEvent.SAVE", properties="customer")]
		public function saveCustomer(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.saveCustomer(customer), onSaveCustomer, onFault);
		}
		
		[EventHandler(event="CustomerEvent.LIST")]
		public function listCustomer():void
		{
			serviceHelper.executeServiceCall(remote.listCustomer(), onListCustomer, onFault);
		}
		
		[EventHandler(event="CustomerEvent.LOAD", properties="customer")]
		public function loadCustomer(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.loadCustomer(customer), onLoadCustomer, onFault);
		}
		
		[EventHandler(event="CustomerEvent.UPDATE", properties="customer")]
		public function updateCustomer(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.updateCustomer(customer), onUpdateCustomer, onFault);
		}
		
		[EventHandler(event="CustomerEvent.DELETE", properties="customer")]
		public function deleteCustomer(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.deleteCustomer(customer), onDeleteCustomer, onFault);
		}
		
		[EventHandler(event="CustomerEvent.SEARCH", properties="customer")]
		public function searchCustomer(customer:CustomerVO):void
		{
			serviceHelper.executeServiceCall(remote.searchCustomer(customer.user.name), onListCustomer, onFault);
		}
		
		
		/**
		 * Result Function
		 */
		
		public function onSaveCustomer(result:ResultEvent):void
		{
			Alert.show("Cliente salvo com sucesso!");
			customer = new CustomerVO(result.result);
		}
		
		public function onLoadCustomer(result:ResultEvent):void
		{
			customer = new CustomerVO(result.result);
		}
		
		public function onListCustomer(result:ResultEvent):void
		{
			dataprovider = new ArrayCollection(result.result as Array);
		}
		
		public function onUpdateCustomer(result:ResultEvent):void
		{
			Alert.show("Cliente alterado com sucesso!");
			customer = new CustomerVO(result.result);
		}
		
		public function onDeleteCustomer(result:ResultEvent):void
		{
			Alert.show("Cliente removido com sucesso!");
			listCustomer();
		}
		
		
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}